package com.nobuyme.box.util;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.Message;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;

public class TcnUtility {

	public static boolean sendEmptyMsg(Handler h, int what) {
		if (null == h) {
			return false;
		}
		
		h.removeMessages(what);
		
    	return h.sendEmptyMessage(what);
    }
	
	public static boolean sendMsgDelayed(Handler h, int what, int arg1, long delayMillis, Object obj) {
		if (null == h) {
			return false;
		}
		
		Message msg = h.obtainMessage();
		
		msg.what	= what;
		msg.arg1	= arg1;
		msg.obj		= obj;
		
		return h.sendMessageDelayed(msg, delayMillis);
    }

	public static boolean sendMsgDelayed(Handler h, int what, int arg1, int arg2, long delayMillis, Object obj) {
		if (null == h) {
			return false;
		}

		Message msg = h.obtainMessage();

		msg.what	= what;
		msg.arg1	= arg1;
		msg.arg2	= arg2;
		msg.obj		= obj;

		return h.sendMessageDelayed(msg, delayMillis);
	}
    
    public static boolean sendMsg(Handler h, int what, int arg1, int arg2, Object obj) {
    	if (null == h) {
    		return false;
    	}
    	
    	//h.removeMessages(what);
    	
		Message msg = h.obtainMessage();
		
		msg.what	= what;
		msg.arg1	= arg1;
		msg.arg2	= arg2;
		msg.obj		= obj;
		
		return h.sendMessage(msg);
	}
    
    public static boolean sendMsgAtFrontOfQueue(Handler h, int what, int arg1, int arg2, Object obj) {
    	if (null == h) {
    		return false;
    	}
    	
    	h.removeMessages(what);
    	
		Message msg = h.obtainMessage();
		
		msg.what	= what;
		msg.arg1	= arg1;
		msg.arg2	= arg2;
		msg.obj		= obj;
		
		return h.sendMessageAtFrontOfQueue(msg);
	}

	public static void removeMessages(Handler h, int what) {
    	if (h != null) {
			h.removeMessages(what);
		}
    }

	/**
	 * 根据格式获取时间 "yyyyMMddHHmmss"
	 * @return
	 */
	public static String getTime(String dataFormat) {
		SimpleDateFormat dateFormat=new SimpleDateFormat(dataFormat);
		return dateFormat.format(new Date(System.currentTimeMillis()));
	}

	public static String getTime14B() {
		SimpleDateFormat dateFormat=new SimpleDateFormat("yyyyMMddHHmmss");
		return dateFormat.format(new Date(System.currentTimeMillis()));
	}

	public static String getTime6B() {
		SimpleDateFormat dateFormat=new SimpleDateFormat("HHmmss");
		return dateFormat.format(new Date(System.currentTimeMillis()));
	}

	/**
	 * 判断是否是含小数
	 * @param str
	 * @return
	 */
	public static boolean isNumerics(String str){
		Pattern pattern = Pattern.compile("^[0-9]+\\.{0,1}[0-9]{0,2}$");
		return pattern.matcher(str).matches();
	}

	/**
	 * 判断是否全部由数字组成
	 * @param str
	 * @return
	 */
	public static boolean isNumeric(String str){
		Pattern pattern = Pattern.compile("^[0-9]*$");
		return pattern.matcher(str).matches();
	}

	/**
	 * 检测网络是否连接
	 *
	 * @return
	 */
	public static boolean isNetConnected(Context context) {
		ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (cm != null) {
			NetworkInfo[] infos = cm.getAllNetworkInfo();
			if (infos != null) {
				for (NetworkInfo ni : infos) {
					if (ni.isConnected() && ni.isAvailable()) {
						return true;
					}
				}
			}
		}
		return false;
	}

	/**
	 *
	 * @param fileName
	 * @return byte[]
	 */
	public static  byte[] readFile(String fileName)
	{
		FileInputStream fis=null;
		ByteArrayOutputStream baos=null;
		byte[] data=null;
		try {
			fis=new FileInputStream(fileName);
			byte[] buffer=new byte[8*1024];
			int readSize=-1;
			baos=new ByteArrayOutputStream();
			while((readSize=fis.read(buffer))!=-1)
			{
				baos.write(buffer, 0, readSize);
			}
			return baos.toByteArray();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}finally
		{
			try {
				if (fis!=null)
				{
					fis.close();
				}
				if (baos!=null)
					baos.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return data;

	}

	/**
	 *
	 * @param data 数据
	 * @param path 路径
	 * @param fileName 文件名
	 * @return true成功 false失败
	 */
	public static boolean writeToSdcard(byte[]data, String path, String fileName)
	{
		FileOutputStream fos=null;
		try {
			//判断有没有文件夹
			File filePath=new File(path);
			if(!filePath.exists())
			{
				//创建文件夹
				filePath.mkdirs();
			}

			//判断有没有同名的文件
			File file=new File(path+fileName);
			//有的话，删除
			if (file.exists())
			{
				file.delete();
			}
			//写文件
			fos=new FileOutputStream(file);
			fos.write(data);
			fos.flush();
			return true;
			//		}

		} catch (Exception e) {
			return false;
			// TODO: handle exception
		}finally
		{
			try {
				if (fos!=null)
					fos.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	/**
	 * 十六进制转换字符串
	 * @return String 对应的字符串
	 */
	public static String hexStr2Str(String hexStr)
	{
		String str = "0123456789ABCDEF";
		char[] hexs = hexStr.toCharArray();
		byte[] bytes = new byte[hexStr.length() / 2];
		int n;

		for (int i = 0; i < bytes.length; i++)
		{
			n = str.indexOf(hexs[2 * i]) * 16;
			n += str.indexOf(hexs[2 * i + 1]);
			bytes[i] = (byte) (n & 0xff);
		}
		return new String(bytes);
	}

	public static String getAmountFen(String strAmount) {
		if (null == strAmount) {
			return null;
		}
		int iPos = strAmount.indexOf(".");
		int iTmpLength = strAmount.length();
		if (iPos != -1) {
			if ((iTmpLength - iPos) == 2) {
				strAmount = strAmount + "0";
			}
		} else {
			strAmount = strAmount + "00";
		}

		String amount = strAmount.replace(".", "");

		return amount;
	}

	/**
	 *@desc 用于金额格式转换
	 *@author Jiancheng,Song
	 *@time 2016/6/6 8:36
	 */
	public static String getAmount6B(String strAmount) {
		if (null == strAmount) {
			return null;
		}
		int iPos = strAmount.indexOf(".");
		int iTmpLength = strAmount.length();
		if (iPos != -1) {
			if ((iTmpLength - iPos) == 2) {
				strAmount = strAmount + "0";
			}
		} else {
			strAmount = strAmount + "00";
		}

		String amount6B = strAmount.replace(".", "");
		int iLength = amount6B.length();
		if (iLength > 6 || iLength < 1) {
			return null;
		}

		for (int i = 0; i < (6 - iLength); i++) {
			amount6B = "0" + amount6B;
		}
		return amount6B;
	}

	/**
	 *@desc 用于金额格式转换
	 *@author Jiancheng,Song
	 *@time 2016/6/6 8:36
	 */
	public static String getAmount12B(String strAmount) {
		if (null == strAmount) {
			return null;
		}
		int iPos = strAmount.indexOf(".");
		int iTmpLength = strAmount.length();
		if (iPos != -1) {
			if ((iTmpLength - iPos) == 2) {
				strAmount = strAmount + "0";
			}
		} else {
			strAmount = strAmount + "00";
		}

		String amount12B = strAmount.replace(".", "");
		int iLength = amount12B.length();
		if (iLength > 12 || iLength < 1) {
			return null;
		}

		for (int i = 0; i < (12 - iLength); i++) {
			amount12B = "0" + amount12B;
		}
		return amount12B;
	}

	/**
	 *@desc 用于金额格式转换
	 *@author Jiancheng,Song
	 *@time 2016/6/6 8:36
	 */
	public static String getAmount10B(String strAmount) {
		if (null == strAmount) {
			return null;
		}
		int iPos = strAmount.indexOf(".");
		int iTmpLength = strAmount.length();
		if (iPos != -1) {
			if ((iTmpLength - iPos) == 2) {
				strAmount = strAmount + "0";
			}
		} else {
			strAmount = strAmount + "00";
		}

		String amount10B = strAmount.replace(".", "");
		int iLength = amount10B.length();
		if (iLength > 10 || iLength < 1) {
			return null;
		}

		for (int i = 0; i < (10 - iLength); i++) {
			amount10B = "0" + amount10B;
		}
		return amount10B;
	}

	public static String getRandomNumber(int length, int start, int end) {
		int iRandomInt = (int)(Math.random() *(end-start+1))+start;
		String strRandom = String.valueOf(iRandomInt);
		int randomLength = strRandom.length();
		if (randomLength > length) {
			strRandom = strRandom.substring(randomLength - length);
		} else {
			for (int i = 0; i < (length - randomLength); i++) {
				strRandom = "0" + strRandom;
			}
		}
		return strRandom;
	}

	/**
	 * 把字节数组转换成16进制字符串
	 *
	 * @param bArray
	 * @return
	 */
	public static String bytesToHexString(byte[] bArray, int byteCount) {
		String stmp = "";
		StringBuilder sb = new StringBuilder("");
		for (int i = 0; i < byteCount; i++) {
			stmp = Integer.toHexString(bArray[i] & 0xFF);
			sb.append((stmp.length()==1)? "0"+stmp : stmp);
		}
		return sb.toString().toUpperCase().trim();
	}

	/* Convert byte[] to hex string.这里我们可以将byte转换成int，然后利用Integer.toHexString(int)来转换成16进制字符串。
            * @param src byte[] data
    * @return hex string
    */
	public static String bytesToHexString(byte[] src){
		StringBuilder stringBuilder = new StringBuilder("");
		if (src == null || src.length <= 0) {
			return null;
		}
		for (int i = 0; i < src.length; i++) {
			int v = src[i] & 0xFF;
			String hv = Integer.toHexString(v);
			if (hv.length() < 2) {
				stringBuilder.append(0);
			}
			stringBuilder.append(hv);
		}
		return stringBuilder.toString();
	}

	/**
	 * Convert hex string to byte[]
	 * @param hexString the hex string
	 * @return byte[]
	 */
	public static byte[] hexStringToBytes(String hexString) {
		if (hexString == null || hexString.equals("")) {
			return null;
		}
		if (hexString.startsWith("0x") || hexString.startsWith("0X")) {
			hexString = hexString.substring(2);
		}
		if (hexString.length() == 1) {
			hexString = "0"+hexString;
		}
		hexString = hexString.toUpperCase();
		int length = hexString.length() / 2;
		char[] hexChars = hexString.toCharArray();
		byte[] d = new byte[length];
		for (int i = 0; i < length; i++) {
			int pos = i * 2;
			d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
		}
		return d;
	}
	/**
	 * Convert char to byte
	 * @param c char
	 * @return byte
	 */
	private static byte charToByte(char c) {
		return (byte) "0123456789ABCDEF".indexOf(c);
	}

	//time   HH:mm
	public static String getHours(String time) {
		String strHour = null;
		if((null != time) && (time.contains(":"))) {
			String[] strarr = time.split(":");
			if ((null != strarr)) {
				if (strarr.length > 1) {
					strHour = strarr[0];
				}
			}
		}
		return strHour;

	}

	//time   HH:mm
	public static String getMinutes(String time) {
		String strMinute = null;
		if((null != time) && (time.contains(":"))) {
			String[] strarr = time.split(":");
			if ((null != strarr)) {
				if (strarr.length > 1) {
					strMinute = strarr[1];
				}
			}
		}
		return strMinute;
	}

	public static String getCheckXOR(String data) {
		String str1 = "00";
		String str2 = "00";
		int iLength = data.length();
		BigInteger big2= new BigInteger(str2, 16);
		for (int i = 0; i < iLength / 2; i++) {
			str1 = data.substring(i*2, (i+1)*2);
			BigInteger big1= new BigInteger(str1, 16);
			big2 = big1.xor(big2);
		}
		String ret = big2.toString(16);
		if (ret.length() == 1) {
			ret = "0" + ret;
		}
		return ret;
	}

	public static String getLengthData(int lentth, String data) {
		if (null == data) {
			return "";
		}
		String strDataLength = String.valueOf(data.length());
		if (strDataLength != null) {
			int iTemp = strDataLength.length();
			if (iTemp < lentth) {
				for (int j = 0; j < (lentth - iTemp); j++) {
					strDataLength = "0"+strDataLength;
				}
			}
		}

		return strDataLength;
	}

	public static long hexStringToDecimal(String hexData) {
		if(hexData==null||hexData.length()<1) {
			throw new RuntimeException("字符串不合法");
		}
		long sum=0;
		int iLength = hexData.length();
		for (int i = 0; i < iLength; i++) {
			long iData = 1 ;
			String tmp = hexData.substring(i,i+1);
			if ("A".equalsIgnoreCase(tmp)) {
				iData = 10;
			} else if ("B".equalsIgnoreCase(tmp)) {
				iData = 11;
			} else if ("C".equalsIgnoreCase(tmp)) {
				iData = 12;
			} else if ("D".equalsIgnoreCase(tmp)) {
				iData = 13;
			} else if ("E".equalsIgnoreCase(tmp)) {
				iData = 14;
			} else if ("F".equalsIgnoreCase(tmp)) {
				iData = 15;
			} else if ("0".equals(tmp)) {
				iData = 0;
			} else if ("1".equals(tmp)) {
				iData = 1;
			} else if ("2".equals(tmp)) {
				iData = 2;
			} else if ("3".equals(tmp)) {
				iData = 3;
			} else if ("4".equals(tmp)) {
				iData = 4;
			} else if ("5".equals(tmp)) {
				iData = 5;
			} else if ("6".equals(tmp)) {
				iData = 6;
			} else if ("7".equals(tmp)) {
				iData = 7;
			} else if ("8".equals(tmp)) {
				iData = 8;
			} else if ("9".equals(tmp)) {
				iData = 9;
			} else {

			}
			for (int j = 0; j < (iLength - i - 1); j++) {
				iData = iData * 16;
			}
			sum = sum + iData;
		}
		return sum;
	}

	/**
	 * MD5加密方法
	 *
	 * @param str
	 * @param encoding
	 *            default UTF-8
	 * @param no_Lower_Upper
	 *            0,1,2 0：不区分大小写，1：小写，2：大写
	 * @return MD5Str
	 */
	public static String getMD5(String str, String encoding, int no_Lower_Upper) {
		if (null == encoding) {
			encoding = "utf-8";
		}
		StringBuffer sb = new StringBuffer();
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			byte[] array = md.digest(str.getBytes(encoding));
			for (int i = 0; i < array.length; i++) {
				sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100)
						.toUpperCase().substring(1, 3));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (no_Lower_Upper == 0) {
			return sb.toString();
		}
		if (no_Lower_Upper == 1) {
			return sb.toString().toLowerCase();
		}
		if (no_Lower_Upper == 2) {
			return sb.toString().toUpperCase();
		}
		return null;
	}

	//其中 -c 1为发送的次数，1为表示发送1次，-w 表示发送后等待响应的时间。
	private static boolean startPing(String ip){
		boolean success=false;
		Process p =null;

		try {
			p = Runtime.getRuntime().exec("ping -c 1 -i 0.2 -W 1 " +ip);
			int status = p.waitFor();
			if (status == 0) {
				success=true;
			} else {
				success=false;
			}
		} catch (IOException e) {
			success=false;
		} catch (InterruptedException e) {
			success=false;
		} finally {
			p.destroy();
		}

		return success;
	}

	private static long lastClickTime;
	public static long getTimeBetween() {
		long time = System.currentTimeMillis();
		long timeD = time - lastClickTime;
		lastClickTime = time;
		return timeD;
	}

}
